<?php

use Illuminate\Database\Seeder;
use App\User;
use App\Wiki;
use App\WikiRevision;
use App\Category;
class WikisTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user_ids = User::all()->pluck('id')->toArray();
        $faker = app(Faker\Generator::class);

        $wikis = factory(Wiki::class)->times(100)
                        ->make()
                        ->each(function ($wiki, $index)
                        use ($user_ids, $faker) {
                            $wiki->founder_id = $faker->randomElement($user_ids);
                            $wiki->cache = json_encode(Wiki::CACHE_FIELDS);
                        });

        Wiki::insert($wikis->toArray());
        // 关联一下分类
        $wiki_ids = Wiki::pluck('id')->all();
        $category_ids = Category::pluck('id')->all();

        foreach ($wiki_ids as $wiki_id) {
            $categories = collect($category_ids)->random(rand(1,5))->toArray();

            $revision = factory(WikiRevision::class)->make()->toArray();
            $revision['user_id'] = $faker->randomElement($user_ids);
            $revision['wiki_id'] = $wiki_id;
            $revision = WikiRevision::create($revision);
            $revision->content()->updateOrCreate(['contentable_id' => $revision->id], ['body' => $faker->text()]);
            $revision->categories()->sync($categories);
            $revision->wiki->categories()->sync($categories);
        }
    }
}
